package controllers

import (
	"acs/management/models"
	"crypto/md5"
	"encoding/hex"
	"encoding/json"
	"errors"
	"io/ioutil"
	"net/http"
	"strconv"
	"time"

	"github.com/labstack/echo"
)

//添加
func AddAPIUSERHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)

	requestbody, requesterr := ioutil.ReadAll(c.Request().Body)
	models.CheckError(requesterr)
	type receiveData struct {
		models.TApiUser
		Step int64 `json:"step"`
		Page int64 `json:"page"`
	}
	//	allStr := c.Param("all")
	var currentData receiveData
	err = json.Unmarshal(requestbody, &currentData)
	models.CheckError(err)
	currentUser := models.CheckLogin(c)

	if currentData.Id > 0 {
		_, err = models.CheckUserPrivilege(&currentUser, models.TableApiUser, 0, models.RoleUpdate)
		models.CheckError(err)
		_, err = models.UpdateTApiUserById(&currentData.TApiUser)
		models.CheckError(err)
		models.AppendLog(&currentUser, "成功修改api user:"+currentData.UserName, models.LOG_TYPE_API_USER)
	} else {
		if models.CheckHasAPIUser(currentData.UserName) == true {
			models.CheckError(errors.New("此访问账户已经存在，请另行更换"))
		}
		m := md5.New()
		m.Write([]byte(currentData.UserName))
		m.Write([]byte(currentData.Password))
		m.Write([]byte(time.Now().String()))
		currentData.Token = hex.EncodeToString(m.Sum(nil))
		_, err = models.CheckUserPrivilege(&currentUser, models.TableApiUser, 0, models.RoleCreate)
		models.CheckError(err)
		_, err = models.AddTApiUser(&currentData.TApiUser)
		models.CheckError(err)
		models.AppendLog(&currentUser, "成功添加api user:"+currentData.UserName, models.LOG_TYPE_API_USER)
	}
	models.PushAPIUser(currentData.UserName, currentData.Token, currentData.Enable == 0)
	models.CheckError(err)
	datalist, totalNum, listErr := models.GetAllTApiUser(nil, nil, nil, nil, int64((currentData.Page-1)*currentData.Step), int64(currentData.Step), true)
	models.CheckError(listErr)
	result := make(map[string]interface{})
	result["apiuserlist"] = datalist
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, currentUser, result, totalNum))
	return
}

//获取
func GetAPIUSERandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	operationIDStr := c.Param("id")
	operationID, swtichErr := strconv.Atoi(operationIDStr)
	models.CheckError(swtichErr)
	currentUser := models.CheckLogin(c)
	_, err = models.CheckUserPrivilege(&currentUser, models.TableApiUser, operationID, models.RoleRead)
	models.CheckError(err)
	operationItem, dbErr := models.GetTApiUserById(int64(operationID))
	models.CheckError(dbErr)
	c.JSON(http.StatusOK, operationItem)
	return
}

//获取列表
func ListAPIUSERHandler(c echo.Context) (err error) {
	defer models.ErrorHandler(c)
	currentPageStr := c.Param("page")
	currentPage, switchErr := strconv.Atoi(currentPageStr)
	models.CheckError(switchErr)

	currentStepStr := c.Param("step")
	currentStep, switchErr2 := strconv.Atoi(currentStepStr)
	models.CheckError(switchErr2)
	if currentPage < 1 || currentStep < 1 {
		panic(errors.New("参数不符合标准。"))
	}
	currentUser := models.CheckLogin(c)
	//	allowList, _ := models.CheckUserPrivilege(&currentUser, models.TableApiUser, 0, models.RoleRead)
	query := make(map[string]interface{})

	datalist, totalNum, listErr := models.GetAllTApiUser(query, nil, nil, nil, int64((currentPage-1)*currentStep), int64(currentStep), true)
	models.CheckError(listErr)
	query = make(map[string]interface{})
	query["apiuserlist"] = datalist
	query["apiuserurl"] = models.GetAllApiUserUrlList()
	c.JSON(http.StatusOK, models.ExportJson(models.Right_Status, currentUser, query, totalNum))
	return
}
